package com.linjian.togetherbirthday.fragment;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.linjian.togetherbirthday.MainActivity;
import com.linjian.togetherbirthday.R;
import com.linjian.togetherbirthday.adapter.base.recyler.ItemWrapper;
import com.linjian.togetherbirthday.adapter.base.recyler.RecyclerAdapter;
import com.linjian.togetherbirthday.adapter.base.recyler.RecyclerHolder;
import com.linjian.togetherbirthday.base.BaseFragment;
import com.linjian.togetherbirthday.bean.HomeActivityDataBean;
import com.linjian.togetherbirthday.contant.HttpContant;
import com.linjian.togetherbirthday.util.LogUtil;
import com.linjian.togetherbirthday.utils.HttpUtils;
import com.linjian.togetherbirthday.utils.NoticeEvent;
import com.linjian.togetherbirthday.utils.SharedPreferencesUtil;
import com.linjian.togetherbirthday.view.sparkbutton.SparkButton;
import com.sdsmdg.tastytoast.TastyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class HomeOneFragment extends BaseFragment implements XRecyclerView.LoadingListener {

    private ImageView backIv;
    private TextView titleTv, rightTv;

    private XRecyclerView mRecyclerView;
    private RecyclerAdapter<HomeActivityDataBean.DataBean> mRecylerAdapter;
    private List<HomeActivityDataBean.DataBean> mList;
    private View mView;

    MainActivity activity;

    public static HomeOneFragment newInstance() {
        HomeOneFragment homeOneFragment = new HomeOneFragment();
        Bundle bundle = new Bundle();
//        bundle.putInt(Integer.class.getName(), resId);
        homeOneFragment.setArguments(bundle);
        return homeOneFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        EventBus.getDefault().register(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
        }
    }

    @Override
    protected int setView() {
        return R.layout.fragment_home_one;
    }

    @Override
    protected void init(View view) {
        mView = view;
        activity = (MainActivity) getActivity();
        mRecyclerView = view.findViewById(R.id.home_one_recyler);
        backIv = view.findViewById(R.id.layout_head_back_iv);
        titleTv = view.findViewById(R.id.layout_head_title_tv);
        rightTv = view.findViewById(R.id.layout_head_right_tv);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);

        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerView.setArrowImageView(R.mipmap.iconfont_downgrey);

        mRecyclerView
                .getDefaultRefreshHeaderView()
                .setRefreshTimeVisible(true);
        mRecyclerView.getDefaultFootView().setLoadingHint("自定义加载中提示");
        mRecyclerView.getDefaultFootView().setNoMoreHint("自定义加载完毕提示");
        mRecyclerView.setLimitNumberToCallLoadMore(1);
        mRecyclerView.setLoadingListener(this);

        mRecylerAdapter = new RecyclerAdapter<HomeActivityDataBean.DataBean>(mItemListener) {
            @Override
            public ItemWrapper getItemHolder(int position) {
                return new ItemWrapper(R.layout.item_date_contant, HomeOneAdapter.class);
            }
        };
        mRecyclerView.setAdapter(mRecylerAdapter);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        backIv.setVisibility(View.GONE);
        titleTv.setText("首页");
        rightTv.setVisibility(View.GONE);
        homeActivity(1);
    }

    private OnItemListener mItemListener = new OnItemListener() {
        @Override
        public void onItemClick(View view, int position) {
            activity.replaceFragment("OnADateInfoFragment", new Gson().toJson(mList.get(position)));
        }

        @Override
        public void collectOnClick(View view, boolean isLike, int position) {
            isLike(homeActivityDataBean.getData().get(position).getEventid(), 1);

        }
    };

    private void isLike(int id, int type) {
        HttpUtils.doGet(HttpContant.URL + HttpContant.ClickRate + "?id=" + id + "&&type=" + type
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("isLike",response.body().string()));
                    }
                }
        );
    }

    HomeActivityDataBean homeActivityDataBean;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMsg(NoticeEvent event) {
        switch (event.getCls()) {
            case "requestFail":
                TastyToast.makeText(getActivity(), "请求失败", TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                break;
            case "homeActivityData":
                LogUtil.e("homeActivityData", event.getData().toString());
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200) {
                        mList = new ArrayList<>();
                        homeActivityDataBean = new Gson().fromJson(event.getData().toString(), HomeActivityDataBean.class);
                        mList.addAll(homeActivityDataBean.getData());
                        mRecylerAdapter.addAll(mList);
                        mRecylerAdapter.notifyDataSetChanged();
                    } else {
                        TastyToast.makeText(getActivity(), object.getString("msg"), TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case "isLike":
                Log.i("isLike",event.getData().toString());
                try {
                    JSONObject object = new JSONObject(event.getData().toString());
                    if (object.getInt("code") == 200){

                    }else {
                        TastyToast.makeText(getActivity(), object.getString("msg"), TastyToast.LENGTH_SHORT, TastyToast.ERROR).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mRecyclerView != null) {
            mRecyclerView.destroy();
            mRecyclerView = null;
        }
    }

    /**
     * 请求首页活动
     */
    private void homeActivity(int currentPage) {

        HttpUtils.doGet(HttpContant.URL + HttpContant.QueryHomeActivity + "?currentPage=" + currentPage
                , "SESSION=" + String.valueOf(SharedPreferencesUtil.get(getActivity(), "Cookie", ""))
                , new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        EventBus.getDefault().post(new NoticeEvent("requestFail"));
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        EventBus.getDefault().post(new NoticeEvent("homeActivityData", response.body().string()));
                    }
                });
    }

    @Override
    public void onRefresh() {
        homeActivity(0);
    }

    @Override
    public void onLoadMore() {

    }


    interface OnItemListener {
        void onItemClick(View view, int position);

        void collectOnClick(View view, boolean isLike, int position);
    }


    static class HomeOneAdapter extends RecyclerHolder<HomeActivityDataBean.DataBean> {

        private TextView releaseTimeTv, nameTv, yearTv, contantTv, addressTv, browseTv, commentsTv, cityTv, dateTimeTv, whyPayTv;
        private ImageView userIv;
        private OnItemListener mItemListener;
        private LinearLayout clickLl;
        private SparkButton giveLikeTv;

        public HomeOneAdapter(View itemView, OnItemListener listener) {
            super(itemView);
            userIv = itemView.findViewById(R.id.item_user_head_img);
            releaseTimeTv = itemView.findViewById(R.id.item_time);
            nameTv = itemView.findViewById(R.id.item_user_head_name);
            yearTv = itemView.findViewById(R.id.item_user_year);
            contantTv = itemView.findViewById(R.id.item_contant);
            addressTv = itemView.findViewById(R.id.item_address);
            browseTv = itemView.findViewById(R.id.item_browse_num);
            commentsTv = itemView.findViewById(R.id.item_comments_num);
            giveLikeTv = itemView.findViewById(R.id.spark_button);
            cityTv = itemView.findViewById(R.id.item_city);
            dateTimeTv = itemView.findViewById(R.id.item_date_time);
            whyPayTv = itemView.findViewById(R.id.item_why_pay);
            clickLl = itemView.findViewById(R.id.item_date_contant_ll);

            mItemListener = listener;

            clickLl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mItemListener.onItemClick(v, getAdapterPosition() - 1);
//                    Log.i("HomeOneFragment","Adapter="+getAdapterPosition()+"layout="+getLayoutPosition()+"position="+getPosition());
                }
            });
//            giveLikeTv.playAnimation();
        }

        @Override
        public void onBindView(HomeActivityDataBean.DataBean dataBean) {
            releaseTimeTv.setText(String.valueOf(dataBean.getCreationtime()));
            nameTv.setText(dataBean.getNickname());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy");
            int year = Integer.valueOf(dataBean.getBirthday().split("-")[0]);
            int newYear = Integer.valueOf(simpleDateFormat.format(new Date()));
            if (dataBean.getSex() == 1) {
                yearTv.setCompoundDrawablesRelativeWithIntrinsicBounds(yearTv.getContext().getResources().getDrawable(R.mipmap.nan_icon), null, null, null);
            } else {
                yearTv.setCompoundDrawablesRelativeWithIntrinsicBounds(yearTv.getContext().getResources().getDrawable(R.mipmap.nv_icon), null, null, null);
            }
            yearTv.setText((newYear - year) + "");
            contantTv.setText(dataBean.getEventexplain());
            addressTv.setText(dataBean.getPlacename());
            commentsTv.setText(dataBean.getEvtNum() + "");
            cityTv.setText(dataBean.getPlacecity());
            String day = dataBean.getEventdate().split("-")[1] + dataBean.getEventdate().split("-")[2].split("T")[0];
            String hour = dataBean.getEventdate().split("-")[2].split("T")[1].split(":")[0] + ":" + dataBean.getEventdate().split("-")[2].split("T")[1].split(":")[1];
            dateTimeTv.setText(day + "  " + hour);
            whyPayTv.setText(dataBean.getCtname());
            releaseTimeTv.setText(dataBean.getCreationtime().split("T")[0]);
            Glide.with(userIv.getContext()).load(dataBean.getHeadimg()).asBitmap().error(R.mipmap.user_pic).placeholder(R.mipmap.user_pic).into(userIv);
            if (dataBean.getIsLike() == 0) {
//                giveLikeTv.setActiveImage(R.mipmap.collect_normal);
//                giveLikeTv.setInactiveImage(R.mipmap.collect_select);
                giveLikeTv.setChecked(false);
            } else {
//                giveLikeTv.setActiveImage(R.mipmap.collect_select);
//                giveLikeTv.setInactiveImage(R.mipmap.collect_normal);
                giveLikeTv.setChecked(true);
            }
            giveLikeTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mItemListener.collectOnClick(v, giveLikeTv.isChecked(), getPosition() - 1);
                    giveLikeTv.playAnimation();
                }
            });
        }
    }
}
